package com.zhejiangzhengyuan.municipal_common.utils.excelFileUtils;

import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

import static com.zhejiangzhengyuan.municipal_common.utils.DateFormatUtil.timeFormat;

/**
 * @author lin_ju
 * @create on 2019/11/28 file 工具类
 */
@Slf4j
public class FileUtil {
  // 获取classPath路径，作为文件根目录
  static String CLASSPATH;

  static {
    if (System.getProperty("os.name").toLowerCase().contains("window")) {
      // 若当前系统是window系统
      CLASSPATH = "c:/municipal/";
    } else {
      CLASSPATH = "/home/municipal/";
    }
  }

  /**
   * 文件上传工具类 成功返回文件可访问路径
   *
   * @param module 请填写模块名 如井盖则填写manhole_cover
   * @param file request 中获取该类型 file
   * @return 若创建成功会返回该文件名，请将其返回给前台
   * @throws IOException 文件创建过程中发生异常会抛出，请手动捕获
   */
  public static String uploadFile(String module, MultipartFile file) throws IOException {
    if (file.isEmpty()|| Strings.isBlank(file.getOriginalFilename())) {
      throw new IOException("文件不存在，请查询携带该文件");
    }
    String fileName = file.getOriginalFilename().split(",")[0];
    File dest =
        new File(CLASSPATH + module + File.separator + System.currentTimeMillis() + "_" + fileName);
    // 文件夹不存在则创建// mkdirs可创建文件夹，mkdir不行
    if (!dest.exists() && !dest.mkdirs()) {
      throw new IOException("文件创建失败");
    }
    file.transferTo(dest);
    return "uploads/" + dest.getAbsolutePath().replaceAll("\\\\", "/").replaceAll(CLASSPATH, "");
  }

  /**
   * 文件删除工具类
   *
   * @param filePath 数据库link字段
   * @throws IOException 文件创建过程中发生异常会抛出，请手动捕获
   */
  public static void removeFile(String filePath) throws IOException {
    filePath = filePath.replaceAll("uploads/", "").replaceAll("/", "\\\\");
    File deleteFile = new File(CLASSPATH + filePath);
    if (!deleteFile.delete()) {
      throw new IOException("文件刪除失败");
    }
  }

  public static com.zhejiangzhengyuan.municipal_common.entity.File getFilePo(
      com.zhejiangzhengyuan.municipal_common.entity.File file,
      String moduleName,
      MultipartFile requestFile)
      throws IOException {
    file = Objects.isNull(file) ? new com.zhejiangzhengyuan.municipal_common.entity.File() : file;
    String uploadFile = uploadFile(moduleName, requestFile);
    log.info(uploadFile);
    String[] strings = uploadFile.split("_");
    file.setLink(uploadFile)
        .setOriginName(strings[strings.length - 1])
        .setVersion(1)
        .setCreateTime(timeFormat(System.currentTimeMillis()))
        .setUpdateTime(timeFormat(System.currentTimeMillis()));
    return file;
  }

  public static String[] getUrlsByRequest(String requestLink){
    if(Strings.isNotBlank(requestLink)){
      return requestLink.replaceAll("\\[","").replaceAll("]","").replaceAll("\"","").split(",");
    }
    return null;
  }
}
